<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-row>
        <el-col :span="18" :xs="24">
          <el-form-item>
            <el-button type="primary" :icon="Plus" v-hasPerm="['sys:user:add']" @click="handleAdd">
              新增用户
            </el-button>
            <el-button type="danger" :icon="Delete" v-hasPerm="['sys:user:del']" :disabled="multiple"
                       @click="handleDelete">{{ $t('gridpannel.index.Delete') }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-form-item prop="keywords">
              <el-input v-model="queryParams.keywords" :placeholder="$t('system.user.number')" clearable
                        style="width: 200px" @keyup.enter="refresh"/>
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="queryParams.status" :placeholder="$t('system.user.status')" clearable
                         style="width: 200px">
                <el-option :label="$t('gridpannel.shareGridPannelDialog.Normal')" value="1"/>
                <el-option :label="$t('system.user.Disable')" value="0"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="refresh">{{
                  $t('system.globalParam.Search')
                }}
              </el-button>
              <el-button :icon="Refresh" @click="resetQuery">{{ $t('system.globalParam.Reset') }}</el-button>
            </el-form-item>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="6" :xs="24" style="text-align: right">-->
        <!--          <el-form-item>-->
        <!--            <el-button :icon="Download" style="margin-left: 12px" @click="handleExport">导出-->
        <!--            </el-button>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>
    </el-form>
    <es-table class="es-table" ref="esTable" :dataGetter="handleQuery"
              header-cell-class-name="app-table-head table-head-center"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column key="id" :label="$t('system.tenant.numberU')" align="center" prop="id"/>
      <el-table-column key="username" :label="$t('system.tenant.nameU')" align="center" prop="username"/>
      <el-table-column :label="$t('system.tenant.nicknameU')" align="center" prop="name"/>
      <el-table-column :label="$t('system.user.Gender')" align="center" prop="sex">
        <template #default="scope">
          <span v-if="scope.row.sex === 1">{{ $t('system.user.Male') }}</span>
          <span v-if="scope.row.sex === 2">{{ $t('system.user.Female') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('system.user.Cell')" align="center" prop="phone" width="120"/>
      <el-table-column :label="$t('gridpannel.shareGridPannelDialog.State')" align="center" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status" :inactive-value="2" :active-value="1"
                     @change="handleStatusChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column :label="$t('gridpannel.index.timeCreate')" align="center" prop="createOn" width="180"/>
      <el-table-column :label="$t('collection.DataCollectionConfiguration.Operation')" align="center" width="150">
        <template #default="scope">
          <Edit class="operation-icon" color="#409eff" @click="handleUpdate(scope.row)"/>
          <Delete class="operation-icon" color="#409eff" @click="handleDelete(scope.row)"/>
          <Lock class="operation-icon" :icon="Lock" color="#409eff" @click="resetPassword(scope.row)"/>
        </template>
      </el-table-column>
    </es-table>
    <!-- 用户表单 -->
    <el-dialog :close-on-click-modal="false" :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body
               @close="cancel">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="auto">
        <el-form-item :label="$t('system.tenant.nameU')" prop="username">
          <el-input :readonly="!!formData.id" v-model="formData.username" :placeholder="$t('system.tenant.nameEuser')"/>
        </el-form-item>
        <el-form-item :label="$t('source.FormJDBC.Password')" prop="password" v-if="!formData.id">
          <el-input type="password" v-model="formData.password" :placeholder="$t('system.tenant.passwordE')"/>
        </el-form-item>
        <el-form-item :label="$t('system.tenant.nicknameU')" prop="name">
          <el-input v-model="formData.name" :placeholder="$t('system.user.nickname')"/>
        </el-form-item>
        <el-form-item :label="$t('system.user.Cell')" prop="phone">
          <el-input v-model="formData.phone" :placeholder="$t('system.user.phone')" maxlength="11"/>
        </el-form-item>
        <el-form-item :label="$t('system.user.Email')" prop="email">
          <el-input v-model="formData.email" :placeholder="$t('system.user.email')" maxlength="50"/>
        </el-form-item>
        <el-form-item :label="$t('gridpannel.shareGridPannelDialog.State')" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">{{ $t('gridpannel.shareGridPannelDialog.Normal') }}</el-radio>
            <el-radio :label="0">{{ $t('system.user.Disable') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('system.user.genderU')" prop="gender">
          <el-select v-model="formData.sex" :placeholder="$t('system.user.select')">
            <el-option :label="$t('system.user.Male')" :value="1"/>
            <el-option :label="$t('system.user.Female')" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('system.user.group')" prop="groupIdList">
          <el-select v-model="formData.groupIdList" multiple :placeholder="$t('system.user.select')">
            <el-option v-for="item in groupOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('system.user.Role')" prop="roleIdList">
          <el-select v-model="formData.roleIdList" multiple :placeholder="$t('system.user.select')">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ $t('gridpannel.addGridPannel.Sure') }}</el-button>
          <el-button @click="cancel">{{ $t('gridpannel.addGridPannel.Cancel') }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// Vue依赖
import {onMounted, reactive, ref, toRefs, unref} from 'vue';
import {UserFormData, UserItem, UserQueryParam} from "@/types/system/user";
import {
  addUser, updateUser, getUserDetail, listUserPages, updateUserStatus, deleteUsers, updateUserPassword
} from "@/services/system/user";
import {Dialog, Option} from "@/types/common";
import {listRole} from "@/services/system/role";
import {ElForm, ElMessage, ElMessageBox} from "element-plus/es";
import {Search, Plus, Edit, Refresh, Delete, Lock, Download, Top, UploadFilled} from '@element-plus/icons-vue';
import {listGroup} from "@/services/system/group";
import EsTable from "@/components/es-table/index.vue";
import {useI18n} from 'vue-i18n'

const {t} = useI18n()
const state = reactive({
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 总条数
  total: 0,
  // 用户分页数据
  userList: [] as UserItem[],
  // 用户组选项
  groupOptions: [] as Option[],
  // 角色选项
  roleOptions: [] as Option[],
  // 弹窗属性
  dialog: {
    visible: false,
  } as Dialog,
  deptName: undefined,
  // 表单参数
  formData: {
    status: 1,
  } as UserFormData,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  } as UserQueryParam,
  rules: {
    username: [{required: true, message: t('system.user.cannotName'), trigger: 'blur'}],
    name: [{required: true, message: t('system.user.cannotnNckname'), trigger: 'blur'},],
    password: [{required: true, message: t('system.user.cannotPassword'), trigger: 'blur'}],
    // groupIdList: [{required: true, message: '用户组不能为空', trigger: 'blur'}],
    roleIdList: [{required: true, message: t('system.user.cannotUser'), trigger: 'blur'}],
    email: [
      {
        pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
        message: t('system.user.emailPlease'),
        trigger: 'blur',
      },
    ],
    phone: [
      {
        required: true,
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: t('system.user.numberPlease'),
        trigger: 'blur',
      },
    ],
  },
});

const {
  loading,
  multiple,
  queryParams,
  userList,
  total,
  roleOptions,
  groupOptions,
  dialog,
  formData,
  rules
} = toRefs(state);

const dataFormRef = ref(ElForm); // 用户表单
const queryFormRef = ref(ElForm); // 查询表单
const esTable = ref()//es-table组件

/**
 * 取消
 */
function cancel() {
  dialog.value.visible = false;
  formData.value.id = undefined;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 * 添加用户
 **/
async function handleAdd() {
  state.dialog = {
    title: t('system.user.userAdd'),
    visible: true,
  };
  await loadRoleOptions();
  await loadGroupOptions();
}

/**
 * 修改用户
 **/
async function handleUpdate(row: { [key: string]: any }) {
  state.dialog = {
    title: t('system.user.userModify'),
    visible: true,
  };
  const userId = row.id || state.ids;
  await loadRoleOptions();
  await loadGroupOptions();
  getUserDetail(userId).then(({data}) => {
    formData.value = data;
  });
}

/**
 * 密码重置
 */
function resetPassword(row: { [key: string]: any }) {
  ElMessageBox.prompt(
      t('system.user.userPlease') + row.username + t('system.user.password'),
      t('system.user.Reset'),
      {
        confirmButtonText: t('system.tenant.Sure'),
        cancelButtonText: t('system.tenant.Cancel'),
      }
  )
      .then(({value}) => {
        if (!value) {
          ElMessage.warning(t('system.user.enterNew'));
          return false;
        }
        updateUserPassword(row.id, value, null).then(() => {
          ElMessage.success(t('system.user.resetSuccessful') + value);
        });
      })
      .catch(() => {
      });
}

/**
 * 删除用户
 */
function handleDelete(row: { [key: string]: any }) {
  const userIds = row.id || state.ids.join(',');
  ElMessageBox.confirm(t('gridpannel.shareGridPannelDialog.deletion') + userIds + t('gridpannel.shareGridPannelDialog.item'), t('system.tenant.Warning'),
      {
        confirmButtonText: t('system.globalParam.Confirm'),
        cancelButtonText: t('system.globalParam.Cancel'),
        type: 'warning',
      }
  ).then(function () {
    deleteUsers(userIds).then(() => {
      ElMessage.success(t('system.tenant.deleteS'));
      unref(esTable).reload()
    });
  }).catch(() => ElMessage.info(t('system.tenant.Undeleted')));
}

/**
 * 表单提交
 */
function submitForm() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = state.formData.id;
      if (userId) {
        updateUser(userId, state.formData).then(() => {
          ElMessage.success(t('system.user.modified'));
          cancel();
          unref(esTable).reload()
        });
      } else {
        addUser(state.formData).then(() => {
          ElMessage.success(t('system.user.addedNew'));
          cancel();
          unref(esTable).reload()
        });
      }
    }
  });
}

/**
 * 用户状态修改
 */
function handleStatusChange(row: { [key: string]: any }) {
  const text = row.status === 1 ? t('system.tenant.Enable') : t('system.tenant.Deactivate');
  ElMessageBox.confirm(t('system.tenant.confirm') + text + '' + row.username + t('system.user.Users'), t('system.tenant.Warning'), {
    confirmButtonText: t('system.tenant.Sure'),
    cancelButtonText: t('system.tenant.Cancel'),
    type: 'warning',
  }).then(() => {
    return updateUserStatus(row.id, row.status);
  }).then(() => {
    ElMessage.success(text + t('system.tenant.Success'));
  }).catch(() => {
    row.status = row.status === 1 ? 2 : 1;
  });
}

const refresh = () => {
  unref(esTable).reload()
}


/**
 * 用户查询
 **/
function handleQuery(page: any) {
  if (page) {
    state.queryParams.pageNum = page.page;
    state.queryParams.pageSize = page.limit;
  }
  return listUserPages(state.queryParams).then(({data}) => {
    return data || {}
  });
}

/**
 * 加载角色下拉列表
 */
async function loadRoleOptions() {
  listRole().then(({data}) => {
    state.roleOptions = data.map(i => {
      return {value: i.id, label: i.roleDesc, checked: false}
    });
  });
}

/**
 * 加载角色下拉列表
 */
async function loadGroupOptions() {
  listGroup().then(({data}) => {
    state.groupOptions = data.map(i => {
      return {value: i.id, label: i.groupName, checked: false};
    });
  });
}

/**
 * 表格行选中事件
 */
function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.single = selection.length !== 1;
  state.multiple = !selection.length;
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  unref(esTable).reload()
}
</script>

<style scoped>

</style>
